package com.saas.auth.handler;

import com.pig4cloud.pig.admin.api.entity.SysLog;
import com.pig4cloud.pig.common.core.constant.SecurityConstants;
import com.pig4cloud.pig.common.core.util.SpringContextHolder;
import com.pig4cloud.pig.common.log.event.SysLogEvent;
import com.pig4cloud.pig.common.log.util.LogTypeEnum;
import com.pig4cloud.pig.common.log.util.SysLogUtils;
import com.pig4cloud.pig.common.security.handler.AbstractAuthenticationFailureEvenHandler;
import com.pig4cloud.pig.common.security.service.PigUser;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

import java.util.Objects;
import java.util.Set;

@Slf4j
@Component
@RequiredArgsConstructor
public class PigAuthenticationFailureEvenHandler extends AbstractAuthenticationFailureEvenHandler {

	private final StringRedisTemplate stringRedisTemplate;

	/**
	 * 处理登录失败方法
	 * <p>
	 * @param authenticationException 登录的authentication 对象
	 * @param authentication 登录的authenticationException 对象
	 */
	@Override
	public void handle(AuthenticationException authenticationException, Authentication authentication) {
		if(Objects.isNull(authentication)){
			return;
		}
		PigUser pigUser = SecurityUtils.getUser(authentication);
		log.info("用户：{} 登录失败，异常：{}", authentication.getPrincipal(), authenticationException.getLocalizedMessage());
		//登录失败，清除解密拦截器中的redis
		// 登录失败 user为null
//		if (Objects.isNull(pigUser)) {
//			this.deleteByKeys(SecurityConstants.CHANGE_PREFIX);
//		} else {
//			stringRedisTemplate.delete(SecurityConstants.CHANGE_PREFIX + pigUser.getUsername());
//		}

		stringRedisTemplate.delete(SecurityConstants.CHANGE_PREFIX + authentication.getPrincipal());

		SysLog logVo = SysLogUtils.getSysLog(null);
		logVo.setTitle("登录失败");
		logVo.setServiceId(authentication.getName());
		logVo.setCreateBy(Objects.isNull(pigUser)?null:pigUser.getUsername());
		logVo.setType(LogTypeEnum.ERROR.getType());
		logVo.setException(authenticationException.getLocalizedMessage());
		SpringContextHolder.publishEvent(new SysLogEvent(logVo));
	}

	private void deleteByKeys(String prex) {
		try {
			Set<String> keys = stringRedisTemplate.keys("*"+prex+"*");
			if (CollectionUtils.isNotEmpty(keys)) {
				stringRedisTemplate.delete(keys);
			}
		}catch (Exception e) {
			e.printStackTrace();
			log.error("批量删除缓存失败{}",prex);
		}
	}

}
